import React, { useState, useEffect, useCallback } from 'react';
import {
  Dialog,
  DialogTitle,
  DialogContent,
  DialogActions,
  Button,
  TextField,
  List,
  ListItem,
  ListItemText,
  IconButton,
  Box,
  Typography,
  Chip,
  Collapse,
  ButtonGroup,
  InputAdornment
} from '@mui/material';
import {
  Add as AddIcon,
  Edit as EditIcon,
  Delete as DeleteIcon,
  ExpandLess,
  ExpandMore,
  Input as InputIcon,
  Output as OutputIcon,
  Search as SearchIcon,
  Clear as ClearIcon
} from '@mui/icons-material';
import AceEditor from 'react-ace';

// 导入 ace 编辑器的必要模块
import 'ace-builds/src-noconflict/mode-json';
import 'ace-builds/src-noconflict/theme-github';
import 'ace-builds/src-noconflict/ext-language_tools';

const API_BASE_URL = process.env.REACT_APP_API_BASE_URL || 'http://localhost:3001';

// 将搜索框组件移到组件外部
const SearchBar = ({ value, onChange, placeholder }) => (
  <Box sx={{ p: 2, borderBottom: '1px solid #eee' }}>
    <TextField
      fullWidth
      size="small"
      placeholder={placeholder}
      value={value}
      onChange={(e) => onChange(e.target.value)}
      InputProps={{
        startAdornment: (
          <InputAdornment position="start">
            <SearchIcon color="action" />
          </InputAdornment>
        ),
        endAdornment: value && (
          <InputAdornment position="end">
            <IconButton
              size="small"
              onClick={() => onChange('')}
              edge="end"
            >
              <ClearIcon />
            </IconButton>
          </InputAdornment>
        ),
        sx: { borderRadius: 2 }
      }}
    />
  </Box>
);

function CustomApiManager({ onSelectSchema }) {
  const [apis, setApis] = useState([]);
  const [openDialog, setOpenDialog] = useState(false);
  const [editingApi, setEditingApi] = useState(null);
  const [expandedApiId, setExpandedApiId] = useState(null);
  const [formData, setFormData] = useState({
    name: '',
    description: '',
    inputSchema: '',
    outputSchema: ''
  });
  const [apiSearchTerm, setApiSearchTerm] = useState('');

  useEffect(() => {
    loadApis();
  }, []);

  const loadApis = async () => {
    try {
      const response = await fetch(`${API_BASE_URL}/api/custom-apis`, {
        headers: {
          'Content-Type': 'application/json',
          // 如果需要凭证
          'credentials': 'include'
        }
      });
      const data = await response.json();
      setApis(data);
    } catch (error) {
      console.error('Error loading APIs:', error);
    }
  };

  const cleanJsonStructure = (jsonString) => {
    try {
      const parsed = JSON.parse(jsonString);
      const cleanStructure = (obj) => {
        if (Array.isArray(obj)) {
          return obj.length > 0 ? [cleanStructure(obj[0])] : [];
        } else if (typeof obj === 'object' && obj !== null) {
          const cleaned = {};
          Object.entries(obj).forEach(([key, value]) => {
            cleaned[key] = cleanStructure(value);
          });
          return cleaned;
        } else {
          switch (typeof obj) {
            case 'string': return '';
            case 'number': return 0;
            case 'boolean': return false;
            default: return null;
          }
        }
      };
      return JSON.stringify(cleanStructure(parsed), null, 2);
    } catch (error) {
      console.error('JSON parsing error:', error);
      return jsonString;
    }
  };

  const handleSubmit = async () => {
    try {
      const cleanedInputSchema = cleanJsonStructure(formData.inputSchema);
      console.log("cleanedInputSchema",cleanedInputSchema);
      const cleanedOutputSchema = cleanJsonStructure(formData.outputSchema);

      const method = editingApi ? 'PUT' : 'POST';
      const url = `${API_BASE_URL}/api/custom-apis${editingApi ? `/${editingApi.id}` : ''}`;

      await fetch(url, {
        method,
        headers: {
          'Content-Type': 'application/json',
          // 如果需要凭证
          'credentials': 'include'
        },
        body: JSON.stringify({
          name: formData.name,
          description: formData.description,
          inputSchema: cleanedInputSchema,
          outputSchema: cleanedOutputSchema
        })
      });

      setOpenDialog(false);
      setEditingApi(null);
      setFormData({
        name: '',
        description: '',
        inputSchema: '',
        outputSchema: ''
      });
      loadApis();
    } catch (error) {
      console.error('Error saving API:', error);
      alert('请确保输入的 JSON 格式正确');
    }
  };

  const handleDelete = async (api) => {
    if (window.confirm('确定要删除这个接口吗？')) {
      try {
        await fetch(`${API_BASE_URL}/api/custom-apis/${api.id}`, { method: 'DELETE' });
        loadApis();
      } catch (error) {
        console.error('Error deleting API:', error);
      }
    }
  };

  const handleEdit = async (api) => {
    try {
      // 获取接口详情
      const response = await fetch(`${API_BASE_URL}/api/custom-apis/${api.id}`, {
        headers: {
          'Content-Type': 'application/json',
          'credentials': 'include'
        }
      });
      
      if (!response.ok) {
        throw new Error('Failed to fetch API details');
      }

      const apiDetails = await response.json();
      console.log('API Details:', apiDetails);

      // 设置编辑状态和表单数据
      setEditingApi(apiDetails);
      setFormData({
        name: apiDetails.name,
        description: apiDetails.description,
        inputSchema: apiDetails.inputSchema ? JSON.stringify(JSON.parse(apiDetails.inputSchema), null, 2) : '',
        outputSchema: apiDetails.outputSchema ? JSON.stringify(JSON.parse(apiDetails.outputSchema), null, 2) : ''
      });
      
      setOpenDialog(true);
    } catch (error) {
      console.error('Error fetching API details:', error);
      alert('获取接口详情失败');
    }
  };

  const handleApiClick = (apiId) => {
    setExpandedApiId(expandedApiId === apiId ? null : apiId);
  };

  const handleJsonChange = (field) => (value) => {
    try {
      if (!value.trim()) {
        setFormData(prev => ({
          ...prev,
          [field]: ''
        }));
        return;
      }

      const parsed = JSON.parse(value);
      const formatted = JSON.stringify(parsed, null, 2);
      setFormData(prev => ({
        ...prev,
        [field]: formatted
      }));
    } catch {
      setFormData(prev => ({
        ...prev,
        [field]: value
      }));
    }
  };

  const addExampleData = (field) => {
    const examples = {
      inputSchema: {
        name: "string",
        age: 0,
        email: "string",
        address: {
          street: "string",
          city: "string",
          country: "string"
        },
        hobbies: ["string"]
      },
      outputSchema: {
        success: true,
        message: "string",
        data: {
          id: 0,
          createdAt: "string",
          updatedAt: "string"
        }
      }
    };

    setFormData(prev => ({
      ...prev,
      [field]: JSON.stringify(examples[field], null, 2)
    }));
  };

  // 添加 JSON 编辑器组件
  const JsonInputField = ({ value, onChange, label, placeholder }) => (
    <Box sx={{ mt: 2 }}>
      <Box sx={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', mb: 1 }}>
        <Typography variant="subtitle1">
          {label} <span style={{ color: 'red' }}>*</span>
        </Typography>
        <Button 
          size="small" 
          onClick={() => addExampleData(label.includes('输入') ? 'inputSchema' : 'outputSchema')}
          variant="outlined"
        >
          添加示例
        </Button>
      </Box>
      <div style={{ border: '1px solid #ddd', borderRadius: '4px', marginBottom: '20px' }}>
        <AceEditor
          mode="json"
          theme="github"
          value={value}
          onChange={onChange}
          name={label}
          editorProps={{ $blockScrolling: true }}
          setOptions={{
            showLineNumbers: true,
            tabSize: 2,
            showPrintMargin: false,
            useWorker: false
          }}
          style={{
            width: '100%',
            height: '200px',
            fontSize: '14px'
          }}
          placeholder={placeholder}
        />
      </div>
    </Box>
  );

  const handleAddToInput = (api, type) => {
    if (type === 'x') {
      // 为新的X输入生成一个唯一的ID (A, B, C...)
      const id = String.fromCharCode(65 + Math.floor(Math.random() * 26));
      
      onSelectSchema({
        type: 'x',
        id: id,
        data: JSON.parse(api.inputSchema)
      });
    } else {
      onSelectSchema({
        type: 'y',
        data: JSON.parse(api.outputSchema)
      });
    }
  };

  // 使用 useCallback 优化搜索处理函数
  const handleSearchChange = useCallback((value) => {
    setApiSearchTerm(value);
  }, []);

  return (
    <Box sx={{ p: 2 }}>
      <Box sx={{ display: 'flex', justifyContent: 'space-between', mb: 2 }}>
        <Typography variant="h6">自定义接口</Typography>
        <Button
          startIcon={<AddIcon />}
          onClick={() => {
            setEditingApi(null);
            setFormData({
              name: '',
              description: '',
              inputSchema: '',
              outputSchema: ''
            });
            setOpenDialog(true);
          }}
          variant="contained"
          color="primary"
        >
          添加接口
        </Button>
      </Box>

      <SearchBar 
        value={apiSearchTerm}
        onChange={handleSearchChange}
        placeholder="搜索接口名称..."
      />

      <List sx={{ width: '100%' }}>
        {apis
          .filter(api => 
            api.name.toLowerCase().includes(apiSearchTerm.toLowerCase()) ||
            api.description?.toLowerCase().includes(apiSearchTerm.toLowerCase())
          )
          .map((api) => (
            <Box key={api.id} sx={{ mb: 1 }}>
              <ListItem
                button
                onClick={() => handleApiClick(api.id)}
                sx={{
                  border: '1px solid #e0e0e0',
                  borderRadius: '4px',
                  mb: 1
                }}
              >
                <Chip
                  label="CUSTOM"
                  size="small"
                  sx={{
                    mr: 2,
                    backgroundColor: '#e3f2fd',
                    color: '#1565c0'
                  }}
                />
                <ListItemText
                  primary={api.name}
                  secondary={api.description}
                  sx={{ flex: 1 }}
                />
                <Box sx={{ display: 'flex', alignItems: 'center' }}>
                  <IconButton
                    onClick={(e) => {
                      e.stopPropagation();
                      handleEdit(api);
                    }}
                    size="small"
                  >
                    <EditIcon />
                  </IconButton>
                  <IconButton
                    onClick={(e) => {
                      e.stopPropagation();
                      handleDelete(api);
                    }}
                    size="small"
                  >
                    <DeleteIcon />
                  </IconButton>
                  {expandedApiId === api.id ? <ExpandLess /> : <ExpandMore />}
                </Box>
              </ListItem>

              <Collapse in={expandedApiId === api.id} timeout="auto" unmountOnExit>
                <Box sx={{ pl: 2, pr: 2, pb: 2, backgroundColor: '#f5f5f5' }}>
                  <Button
                    variant="contained"
                    size="small"
                    sx={{ mr: 1, mb: 1 }}
                    onClick={() => handleAddToInput(api, 'x')}
                  >
                    添加为X输入
                  </Button>
                  <Button
                    variant="contained"
                    size="small"
                    onClick={() => handleAddToInput(api, 'y')}
                  >
                    设为Y输出
                  </Button>
                </Box>
              </Collapse>
            </Box>
          ))}
      </List>

      <Dialog open={openDialog} onClose={() => setOpenDialog(false)} maxWidth="md" fullWidth>
        <DialogTitle>
          {editingApi ? '编辑接口' : '添加接口'}
        </DialogTitle>
        <DialogContent>
          <TextField
            fullWidth
            label="接口名称"
            value={formData.name}
            onChange={(e) => setFormData({ ...formData, name: e.target.value })}
            margin="normal"
            required
          />
          <TextField
            fullWidth
            label="描述"
            value={formData.description}
            onChange={(e) => setFormData({ ...formData, description: e.target.value })}
            margin="normal"
            multiline
            rows={2}
          />
          
          <JsonInputField
            label="输入参数结构 (JSON格式)"
            value={formData.inputSchema}
            onChange={(value) => setFormData(prev => ({ ...prev, inputSchema: value }))}
            placeholder="请输入JSON格式的输入参数结构"
          />
          
          <JsonInputField
            label="输出参数结构 (JSON格式)"
            value={formData.outputSchema}
            onChange={(value) => setFormData(prev => ({ ...prev, outputSchema: value }))}
            placeholder="请输入JSON格式的输出参数结构"
          />
        </DialogContent>
        <DialogActions>
          <Button onClick={() => setOpenDialog(false)}>取消</Button>
          <Button 
            onClick={handleSubmit} 
            variant="contained"
            disabled={!formData.name || !formData.inputSchema || !formData.outputSchema}
          >
            保存
          </Button>
        </DialogActions>
      </Dialog>
    </Box>
  );
}

export default CustomApiManager; 